package com.lrj.datastructure.calendar;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;

//万年历查询：https://wannianli.tianqi.com/2020/01/
public abstract class Calendar {
    protected int year = 0;
    protected int month = 0;

    //输入年份和月份
    public void inputYearAndMonth() {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        try {
            //输入年份
            System.out.print("请输入年份：");
            String yearStr = reader.readLine();
            this.year = Integer.parseInt(yearStr);
            //输入月份
            System.out.print("请输入月份：");
            String monthStr = reader.readLine();
            this.month = Integer.parseInt(monthStr);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //打印日历
    public void print() {
        if (this.year == 0 || month == 0) {
            inputYearAndMonth();
        }

        //获取year年month月01日是星期几（0表示星期天，1~6表示星期一 ~ 星期六）
        int week = getWeek();
        //获取month月的天数
        int days = getMonthDays(month, year);
        //打印的字符串
        String msg = "日\t一\t二\t三\t四\t五\t六\n";
        //前置空格
        for (int i = 0; i < week; i ++) {
            msg += '\t';
        }
        //拼接日历
        for (int i = 0; i < days; i ++) {

            msg += (i + 1) + "\t";
            week = (week + 1) % 7;
            if (week == 0) {
                msg += "\n";
            }
        }

        //打印字符串
        System.out.println(msg);
    }

    //获取month月的天数
    protected int getMonthDays(int month, int year) {
        //平年
        int[] commonYearMonths = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
        //闰年
        int[] leapYearMonths = {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

        if (isLyeap(year)) {
            return leapYearMonths[month - 1];
        } else {
            return commonYearMonths[month - 1];
        }
    }

    //获取year是否为闰年
    protected boolean isLyeap(int year) {
        //闰年有两种情况
        //1、只要能被400整除的都是闰年
        //2、如果不能被400整除，则只要是能被4整除，但不能被100整除的，都是闰年
        return year % 400 == 0 || (year % 4 == 0 && year % 100 != 0);
    }

    //获取year年month月01日是星期几
    protected abstract int getWeek();

    public int getYear() {
        return year;
    }

    public void setYear(int year) {
        this.year = year;
    }

    public int getMonth() {
        return month;
    }

    public void setMonth(int month) {
        this.month = month;
    }
}
